import Vuex from 'vuex';
import Vue from 'vue';
import {
	http
} from '@/api/service.js'
import {
	login,
	getTeacherInfo,
	getParentInfo
} from '@/api/user.js'
import {
	removeTicket
} from '@/utils/auth'

const state = {
	tchInfo: null,
	parentInfo: null,
}

const getters = {
	upload: state => {
		let item = {};
		item.baseURL = http.config.baseURL;
		item.header = {
			ticket: uni.getStorageSync('ticket'),
		};
		return item;
	},
	
	findMenuList: (state) => (perms) => {
		return new Promise(resolve => {
			const menuFn = (menu, perms) => {
				// console.log(menu)
				if (menu.perms === perms) {
					resolve(menu)
				} else {
					if (menu.children && menu.children.length > 0) {
						for (let index in menu.children) {
							let item = menu.children[index];
							menuFn(item, perms);
						}
					}
				}
			}
			return menuFn(state.tchInfo.menuList[0], perms);
		})
	},

}

const mutations = {
	setTeacherInfo(state, user) {
		state.tchInfo = user;
		uni.setStorage({
			key: 'tchInfo',
			data: JSON.stringify(user)
		});
	},
	
	setParentInfo(state, user) {
		state.parentInfo = user;
		uni.setStorage({
			key: 'parentInfo',
			data: JSON.stringify(user)
		});
	},

	updateTeacherHeadImgUrl(state, url) {
		state.tchInfo.staff.headImgUrl = url;
		uni.setStorage({
			key: 'tchInfo',
			data: JSON.stringify(state.tchInfo)
		});
	},
	
	updateChildrenHeadImgUrl(state, url) {
		state.parentInfo.defaultBaby.imgUrl = url;
		uni.setStorage({
			key: 'parentInfo',
			data: JSON.stringify(state.parentInfo)
		});
	},
	
	setTeacherDefaultRole(state, role) {
		state.tchInfo.role = role;
		state.tchInfo.defaultRole = role;
		uni.setStorage({
			key: 'tchInfo',
			data: JSON.stringify(state.tchInfo)
		});
	},

	logout(state) {
		state.tchInfo = null;
		state.parentInfo = null;
		removeTicket();
		uni.setStorage({
			key: 'tchInfo',
			data: ''
		});
		uni.setStorage({
			key: 'parentInfo',
			data: ''
		});
	},
}

const actions = {
	refreshTeacherInfo(context, {
		callback
	}) {
		getTeacherInfo().then(res => {
			console.log(res);
			context.commit('setTeacherInfo', res.data);
			if (callback) callback()
		})
	},
	
	refreshParentInfo(context, {
		callback
	}) {
		getParentInfo().then(res => {
			console.log(res);
			context.commit('setParentInfo', res.data);
			if (callback) callback()
		})
	},
	
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
